package com.example.serialportdemo;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.BRMicro.NETLH_E;

import java.util.ArrayList;
import java.util.List;

public class RegisterActivity extends AppCompatActivity {
    private boolean flag;
    private void setCancel(boolean cancel){
        this.flag=cancel;
    }
    /*单例*/
    private static NETLH_E netlh_e=NETLH_E.getInstance();
    /*XML控件*/
    private Button fingerPrint_in,compare,search,clear,delete;
    public static TextView tips;
    private static ListView fingerPrint_database;
    /*ListView*/
    public ArrayAdapter adapter;
    private List<String> list=new ArrayList<String>();
    private static int pos;
    private static String data_address="";//指纹库编号ID

    /*函数实参*/
    private byte[] CmdGetMBIndex_gMBIndex=new byte[100];//存放获取到的指纹模板索引
    private int[] CmdGetMBIndex_ErrFlag=new int[1];//读取指纹模板索引结果返回

    private Dialog dialog;//输入地址对话框

    /*自定义函数*/
    private  void makeToastByRunOnUiThread(final String str)//更新UI
    {
        RegisterActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tips.setText(str);
            }
        });
    }

    private  void addlist(final String str)//增加指纹ID
    {
        RegisterActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.add(str);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private  void removelist(int position)//删除指纹ID
    {
        RegisterActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private  void clearlist()//清除指纹ID库
    {
        RegisterActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.clear();
                adapter.notifyDataSetChanged();
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        Init();
        InitonClick();
        /**/
        netlh_e.CmdGetMBIndex(CmdGetMBIndex_gMBIndex,0,90,CmdGetMBIndex_ErrFlag);//读取指纹模板索引
        for(int i=0;i<90;i++){
            if(CmdGetMBIndex_gMBIndex[i]==1){
                list.add(i+"");
            }
        }
        adapter=new ArrayAdapter(RegisterActivity.this, R.layout.list_item, list);
        fingerPrint_database.setAdapter(adapter);
    }

    public void Init(){
        fingerPrint_in=findViewById(R.id.btn_fingerprint_input);
        tips=findViewById(R.id.tv_tips);
        compare=findViewById(R.id.btn_compare);
        search=findViewById(R.id.btn_search);
        delete=findViewById(R.id.btn_delete);
        clear=findViewById(R.id.btn_clear);
        fingerPrint_database=findViewById(R.id.lv_fingerprint_database);
    }

    public void InitonClick(){
        fingerPrint_in.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                EditText address=new EditText(RegisterActivity.this);
                address.setInputType(InputType.TYPE_CLASS_NUMBER);
                dialog=new AlertDialog.Builder(RegisterActivity.this)
                        .setTitle("请输入编号")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setView(address)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new fingerPrint_Thread(address.getText().toString()).start();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();
            }
        });

        fingerPrint_database.setOnItemClickListener(new AdapterView.OnItemClickListener() {             //获取ListView点击
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pos=position;
                data_address=list.get(position);
                Log.d("pos",pos+"");
                Log.d("data_address",data_address);
            }
        });
        compare.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                compareThread.start();
            }
        });
        search.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                searchThread.start();
            }
        });
        clear.setOnClickListener(new View.OnClickListener(){      //清空数据库
            @Override
            public void onClick(View v) {
                int[] CmdEmptyChar_ErrFlag=new int[1];
                netlh_e.CmdEmptyChar(CmdEmptyChar_ErrFlag);
                if(CmdEmptyChar_ErrFlag[0]==0){
                    makeToastByRunOnUiThread("清空成功");
                    clearlist();
                }
               else if(CmdEmptyChar_ErrFlag[0]==0x0f){
                    makeToastByRunOnUiThread("清空失败");
                }
            }
        });
        delete.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                int[] CmdDelChar_ErrFlag=new int[1];
                if(data_address.length()>0){
                    netlh_e.CmdDelChar(Integer.parseInt(data_address),CmdDelChar_ErrFlag);
                    if(CmdDelChar_ErrFlag[0]==0){
                        makeToastByRunOnUiThread("删除成功");
                        removelist(pos);
                    }
                    else{
                        makeToastByRunOnUiThread("删除失败");
                    }
                }
            }
        });
    }
    Thread searchThread=new Thread(new Runnable() {
        @Override
        public void run() {
            setCancel(false);
            int[] CmdGetRedressImage_ErrFlag={-1};
            int[] CmdGenChar_ErrFlag={-1};
            int[] CmdSearchChar_RetMbIndex={-1};
            int[] CmdSearchChar_RetScore={-1};
            int[] CmdSearchChar_ErrFlag={-1};
            makeToastByRunOnUiThread("开始录入指纹");
            while (!flag){
                netlh_e.CmdGetRedressImage(0,CmdGetRedressImage_ErrFlag);
                if(CmdGetRedressImage_ErrFlag[0]==0){
                    setCancel(true);
                    makeToastByRunOnUiThread("请移开手指");
                    netlh_e.CmdGenChar(1,CmdGenChar_ErrFlag);
                    if(CmdGenChar_ErrFlag[0]==0){
                        netlh_e.CmdSearchChar(1,CmdSearchChar_RetMbIndex,CmdSearchChar_RetScore,CmdSearchChar_ErrFlag);
                        if(CmdSearchChar_ErrFlag[0]==0) {
                            makeToastByRunOnUiThread("搜索到相同指纹，ID为："+CmdSearchChar_RetMbIndex[0]);
                            return;
                        }
                        else{
                            makeToastByRunOnUiThread("未搜索到相同指纹");
                            return;
                        }
                    }
                    else{
                        makeToastByRunOnUiThread("搜索失败");
                        return;
                    }
                }
            }
            return;
        }
    });

     Thread compareThread=new Thread(new Runnable() {
        @Override
        public void run() {
            setCancel(false);
            int[] CmdGetRedressImage_ErrFlag=new int[1];
            int[] CmdGenChar_ErrFlag=new int[1];
            int[] CmdVerifyChar_RetScore=new int[1];
            int[] CmdVerifyChar_ErrFlag=new int[1];
            if(data_address.length()>0){
                makeToastByRunOnUiThread("开始录入指纹");
                while (!flag) {
                    netlh_e.CmdGetRedressImage(0,CmdGetRedressImage_ErrFlag);
                    if(CmdGetRedressImage_ErrFlag[0]==0){
                        makeToastByRunOnUiThread("请移开手指");
                        setCancel(true);
                        netlh_e.CmdGenChar(1,CmdGenChar_ErrFlag);
                        if(CmdGenChar_ErrFlag[0]==0){
                            netlh_e.CmdVerifyChar(1,Integer.parseInt(data_address),CmdVerifyChar_RetScore,CmdVerifyChar_ErrFlag);
                            if(CmdVerifyChar_ErrFlag[0]==0) {
                                makeToastByRunOnUiThread("比对符合");
                            }
                            else{
                                makeToastByRunOnUiThread("比对不符合");
                            }
                        }
                        else{
                            makeToastByRunOnUiThread("比对失败");
                        }
                    }
                }
            }
            return;
        }
    });
     class fingerPrint_Thread extends Thread{
         String str;
         fingerPrint_Thread(String str){
             this.str=str;
         }
             @Override
             public void run() {
                 int[] CmdGetRedressImage_ErrFlag={-1};
                 int[] CmdGenChar_ErrFlag={-1};
                 int[] CmdMergeChar_Score={-1};
                 int[] CmdMergeChar_Errflag={-1};
                 int[] CmdStoreChar_RetMbIndex={-1};
                 int[] CmdStoreChar_RetScore={-1};
                 int[] CmdStoreChar_ErrFlag={-1};
                 for (int i=1;i<4;i++){
                     setCancel(false);
                     makeToastByRunOnUiThread("开始录入指纹");
                     while (!flag){
                         netlh_e.CmdGetRedressImage(0,CmdGetRedressImage_ErrFlag);
                         Log.d("Register",CmdGetRedressImage_ErrFlag[0]+"");
                         if(CmdGetRedressImage_ErrFlag[0]==0){//判断图像是否采集成功
                             setCancel(true);
                             netlh_e.CmdGenChar(i,CmdGenChar_ErrFlag);//生成指纹特征
                             if(CmdGenChar_ErrFlag[0]!=0){
                                 return;
                             }
                         }
                         CmdGetRedressImage_ErrFlag[0]=-1;
                     }
                 }
                 netlh_e.CmdMergeChar(CmdMergeChar_Score,CmdMergeChar_Errflag);//合并指纹特征
                 if(CmdMergeChar_Errflag[0]==0){//判断合并是否完成
                     netlh_e.CmdStoreChar(Integer.parseInt(str),CmdStoreChar_RetMbIndex,CmdStoreChar_RetScore,CmdStoreChar_ErrFlag);//存储指纹模板
                     if(CmdStoreChar_ErrFlag[0]==0){
                         makeToastByRunOnUiThread("录入成功");
                         addlist(str);//添加指纹ListView显示
                     }
                     else{
                         makeToastByRunOnUiThread("录入失败");
                     }
                 }
                 else {
                     makeToastByRunOnUiThread("录入失败");
                 }
                 return;
             }
     }
}